package com.cloudpivot.receivales.contract.util;

import com.cloudpivot.receivales.meta.bsweaverdocws.DocAttachment;
import com.cloudpivot.receivales.meta.bsweaverdocws.DocInfo;
import com.cloudpivot.receivales.meta.bsweaverdocws.DocServiceLocator;
import com.cloudpivot.receivales.meta.bsweaverdocws.DocServicePortType;
import org.apache.axis.encoding.Base64;
import org.springframework.stereotype.Service;

import javax.xml.rpc.ServiceException;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import java.io.*;

@Service
public class GetDocumentUtil {
    private static DocServicePortType service = null;

    private static String fullPath = "/data/contractproject/fontMode/tmp";

    private String serviceurl = "http://172.16.0.201/services/DocService";


    private String loginname="sysadmin";


    private String loginpassword="biosan@2202";


    private String loginip = "172.16.0.201";

    public File getDocfile(int docid){
        try {
        service = new DocServiceLocator().getDocServiceHttpPort(new URL(serviceurl));

        // 登陆
        String loginid = loginname;
        String password = loginpassword;
        int logintype = 0;
        String ip = loginip;
        String session = getSession(loginid,password,logintype,ip);
        System.out.println(session);

        return getDocInfo(session,docid);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static File getDocInfo(String session, int docid) throws RemoteException {

        // 根据ID取得文档内容 ，docid 为文档的id
        DocInfo doc = service.getDoc(docid, session);

        // 取得该文档的第一个附件
        DocAttachment da = doc.getAttachments()[0];
        // 得到附件内容并解码
        byte[] content = Base64.decode(da.getFilecontent());

        // 将附件内容转存至本地文件
        File file = new File(fullPath + da.getFilename());
        try {
            int byteread;
            byte[] data = new byte[1024];
            InputStream imagefile = new ByteArrayInputStream(content);

            OutputStream out = new FileOutputStream(file);
            while ((byteread = imagefile.read(data)) != -1) {
                out.write(data, 0, byteread);
                out.flush();
            }

            imagefile.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null; // 捕获异常时返回null
        }

        return file; // 返回生成的文件
    }
    public static String getSession(String loginid,String password,int logintype,String ip) throws MalformedURLException, ServiceException, RemoteException{
        // 登陆
        String session = service.login(loginid, password, logintype, ip);//用户名，密码，登陆方式(0 数据库验证;1 动态密码验证;2 LDAP验证)，ip

        return session;
    }


}
